<template>
	<view>
		<view class="content">
			<view class="uolds">
				<image src="/static/my/sc.png" mode="widthFix"></image>
				<view class="title">请上传需要申报平台的营业额相关报表</view>
				<view class="tsg">支持格式为Excel</view>
				<view class="btn" :class="{ 'uploading': uploading }" @click="chooseAndUploadFile">
					{{ uploading ? '上传中...' : '+上传本地表格' }}
				</view>
			</view>
			
			<!-- 文件名显示区域 -->
<!-- 			<view class="file-name-display" v-if="fileName">
				<text class="fa fa-file-excel-o"></text>
				<text class="file-name-text">{{ fileName }}</text>
				<view class="delete-btn" v-if="uploadResult" @click="deleteFile">
					<text class="fa fa-trash-o"></text>
				</view>
			</view> -->
			
			<!-- 上传进度条 -->
			<view class="progress-container" v-if="uploading">
				<view class="progress-bar">
					<view class="progress-inner" :style="{ width: uploadProgress + '%' }"></view>
				</view>
				<view class="progress-text">{{ uploadProgress }}%</view>
			</view>
			
			<!-- 上传结果区域 -->
			<view class="upload-result" v-if="uploadResult">
				<view class="file-info">
					<text class="fa fa-file-excel-o"></text>
					<view class="file-name">{{ uploadResult.name || fileName }}</view>
					<view class="file-size">{{ formatSize(uploadResult.size) }}</view>
				</view>
				<view class="upload-success">
					<text class="fa fa-check-circle"></text>
					<text>上传成功</text>
				</view>
				<view class="delete-file-btn" @click="deleteFile">
					删除文件
				</view>
			</view>
			
			<!-- 上传错误提示 -->
			<view class="upload-error" v-if="uploadError">
				<text class="fa fa-exclamation-circle"></text>
				<text>{{ uploadError }}</text>
			</view>
			<view class="gz">
				规则说明：
			</view>
			<view class="text">说明</view>
		</view>
		<view class="cofing" @click="submitForm" :disabled="!uploadResult">
			提交报表 
		</view>
	</view>
</template>

<script>
import { merchantReport } from '@/core/api/index.js'
import { mapState } from 'vuex';
export default {
  data() {
    return {
      uploading: false,        // 是否正在上传
      uploadResult: null,      // 上传结果
      uploadError: '',         // 上传错误信息
      uploadProgress: 0,       // 上传进度百分比
      uploadUrl: 'https://shequ.shihongkeji.cn/webapi/file/upload', // 上传接口地址
      fileName: '',             // 文件名
      isDeleting: false         // 删除中状态
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    // 选择并上传文件
    chooseAndUploadFile() {
      if (this.uploading || this.isDeleting) return;
      
      uni.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['xlsx', 'xls'],  // 限制为Excel文件
        success: (res) => {
          const file = res.tempFiles[0];
          this.fileName = file.name; // 显示选择的文件名
          this.startUpload(file);
        },
        fail: (err) => {
          this.uploadError = '选择文件失败，请重试';
          this.fileName = ''; // 清空文件名
          setTimeout(() => {
            this.uploadError = '';
          }, 3000);
        }
      });
    },
    // 开始上传文件
    startUpload(file) {
      this.uploading = true;
      this.uploadProgress = 0;
      this.uploadError = '';
      this.uploadResult = null;
      
      const uploadTask = uni.uploadFile({
        url: this.uploadUrl,
        filePath: file.path,
        name: 'file',
        formData: {
          fileName: file.name
        },
        success: (res) => {
          const result = JSON.parse(res.data);
          if (result.code == '00000') {
            this.uploadResult = {
              size: file.size,
              url: result.result.filePath,
              serverFileName: result.result.fileName || file.name // 服务器返回的文件名
            };
          } else {
            this.uploadError = result.message || '上传失败';
          }
        },
        fail: (err) => {
          this.uploadError = '上传失败：网络错误';
        },
        complete: () => {
          this.uploading = false;
          this.uploadProgress = 0;
          
          if (!this.uploadResult) {
            this.fileName = '';
          }
          
          if (this.uploadError) {
            setTimeout(() => {
              this.uploadError = '';
            }, 3000);
          }
        }
      });
      
      uploadTask.onProgressUpdate((progressRes) => {
        this.uploadProgress = progressRes.progress;
      });
    },
    
    // 删除文件
    deleteFile() {
      if (this.isDeleting) return;
      
      uni.showModal({
        title: '确认删除',
        content: '确定要删除已上传的文件吗？',
        success: (res) => {
          if (res.confirm) {
            this.isDeleting = true;
            this.uploadError = '';
            
            // 显示删除中状态
            this.uploadResult = null;
            this.fileName = '';
            
            // 这里可以添加服务器删除文件的API调用
            // 示例：
            // uni.request({
            //   url: 'https://your-api.com/deleteFile',
            //   method: 'POST',
            //   data: { fileId: this.uploadResult.id },
            //   success: (res) => {
            //     if (res.data.code === 0) {
            //       uni.showToast({ title: '删除成功', icon: 'success' });
            //     } else {
            //       uni.showToast({ title: res.data.message || '删除失败', icon: 'none' });
            //     }
            //   },
            //   fail: () => {
            //     uni.showToast({ title: '删除失败：网络错误', icon: 'none' });
            //   },
            //   complete: () => {
            //     this.isDeleting = false;
            //   }
            // });
            
            // 模拟删除成功
            setTimeout(() => {
              this.isDeleting = false;
              uni.showToast({
                title: '删除成功',
                icon: 'success'
              });
            }, 800);
          }
        }
      });
    },
    
    // 提交表单
    async submitForm() {
      if (!this.uploadResult) {
        uni.showToast({
          title: '请先上传文件',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '提交中...'
      });
	  let prmes = {
		  filePath:this.uploadResult.url,
		  merchantId:this.userInfo.shopId,
		  merchantName:this.userInfo.shopName
	  }
      const data = await merchantReport(prmes)
	  console.log(data)
	  if(data.code == '00000'){
		setTimeout(() => {
		    uni.hideLoading();
		    uni.showToast({
		      title: '提交成功',
		      icon: 'success'
		    });
		    setTimeout(() => {
		      uni.navigateBack();
		    }, 2000);
		  }, 1500);
		}else{
			uni.showToast({
			  title: data.msg,
			  icon: 'none'
			});
		}
	  },
    
    // 格式化文件大小
    formatSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
}
</script>

<style lang="scss">
	.content{
		background-color: #fff;
		margin: 20rpx 30rpx;
		padding: 45rpx 40rpx;
		.uolds{
			border-radius: 12rpx;
			border: 1px dashed #C8C8C8;
			background: rgba(202, 202, 202, 0.10);
			height: 346rpx;
			display: flex;
			align-items: center;
			padding-bottom: 15rpx;
			justify-content: center;
			flex-direction: column;
			image{
				width: 116rpx;
			}
			.title , .tsg{
				font-weight: 500;
                font-size: 28rpx;
			}
			.tsg{
				color: #A3A3A3;
			}
			.btn{
				margin-top: 34rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 240rpx;
				height: 80rpx;
				border: 1px solid #E5E5E5;
				border-radius: 8rpx;
				background: rgba(242, 107, 46, 0.09);
				cursor: pointer;
				transition: all 0.3s;
				
				&.uploading {
					background: rgba(242, 107, 46, 0.2);
					color: #F26B2E;
				}
			}
		}
		.gz{
			margin-top: 40rpx;
		}
		.text{
			color: var(--, #A3A3A3);
            font-size: 24rpx;
			margin-top: 10rpx;
		}
		
		// 文件名显示区域
		.file-name-display {
			display: flex;
			align-items: center;
			margin: 20rpx 0;
			padding: 15rpx 20rpx;
			background-color: #F9F9F9;
			border-radius: 8rpx;
			font-size: 26rpx;
			color: #333;
			
			.fa-file-excel-o {
				color: #F26B2E;
				font-size: 30rpx;
				margin-right: 10rpx;
			}
			
			.file-name-text {
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				max-width: 70%;
			}
			
			.delete-btn {
				margin-left: auto;
				width: 40rpx;
				height: 40rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				color: #ff4d4f;
				font-size: 28rpx;
			}
		}
		
		// 上传进度条样式
		.progress-container {
			margin: 30rpx 0;
			padding: 10rpx 0;
			
			.progress-bar {
				width: 100%;
				height: 8rpx;
				background-color: #E5E5E5;
				border-radius: 4rpx;
				overflow: hidden;
				
				.progress-inner {
					height: 100%;
					background-color: #F26B2E;
					border-radius: 4rpx;
					transition: width 0.2s;
				}
			}
			
			.progress-text {
				font-size: 24rpx;
				color: #999;
				text-align: center;
				margin-top: 10rpx;
			}
		}
		
		// 上传结果样式
		.upload-result {
			margin-top: 30rpx;
			padding: 20rpx;
			background-color: rgba(33, 181, 83, 0.05);
			border-radius: 12rpx;
			
			.file-info {
				display: flex;
				align-items: center;
				
				.fa-file-excel-o {
					color: #217346;
					font-size: 36rpx;
					margin-right: 15rpx;
				}
				
				.file-name {
					font-size: 28rpx;
					color: #333;
					max-width: 450rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				
				.file-size {
					font-size: 24rpx;
					color: #999;
					margin-left: 20rpx;
				}
			}
			
			.upload-success {
				margin-top: 15rpx;
				color: #21B553;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				
				.fa-check-circle {
					margin-right: 10rpx;
				}
			}
			
			.delete-file-btn {
				margin-top: 20rpx;
				color: #ff4d4f;
				font-size: 26rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				height: 40rpx;
				border-top: 1rpx solid #e5e5e5;
				padding-top: 15rpx;
			}
		}
		
		// 上传错误样式
		.upload-error {
			margin-top: 30rpx;
			padding: 20rpx;
			background-color: rgba(255, 59, 48, 0.05);
			border-radius: 12rpx;
			color: #FF3B30;
			font-size: 26rpx;
			display: flex;
			align-items: center;
			
			.fa-exclamation-circle {
				margin-right: 10rpx;
			}
		}
	}
	
	.cofing{
		height: 88rpx;
		background-color: #F26B2E;
		text-align: center;
		border-radius: 50rpx;
		color: #fff;
		font-size: 32rpx;
		line-height: 79rpx;
		margin: 40rpx 30rpx;
		cursor: pointer;
		opacity: 1;
		transition: all 0.3s;
		
		&[disabled] {
			background-color: #E5E5E5;
			color: #999;
			cursor: not-allowed;
		}
	}
</style>